class_name Interactable
extends Area2D

@export var disabled := false
@export var auto_activate := false

var action: Callable


func init_interactable() -> void:
	pass


func _ready() -> void:
	for player in get_tree().get_nodes_in_group("player"):
		player.interact.connect(on_interact)
	body_entered.connect(_on_body_entered)
	body_exited.connect(_on_body_exited)
	
	collision_layer = 0
	collision_mask = 0
	set_collision_layer_value(4, true)
	set_collision_mask_value(1, true)

	init_interactable()


func _on_body_entered(body: Node2D) -> void:
	Data.player_interact_with.append(name)
	print("%s is detected by %s" % [body.name, name])
	if auto_activate: on_interact()


func _on_body_exited(_body: Node2D) -> void:
	Data.player_interact_with.erase(name)


func on_interact() -> void:
	if !Data.player_interact_with:
		return
	if Data.player_interact_with.back() != name or disabled:
		return
	if action: 
		action.call()
	else:
		print("Interact with %s" % name)
